// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { voteId } = event

  if (!voteId) {
    return {
      success: false,
      message: '投票ID不能为空'
    }
  }

  try {
    // 获取投票活动详情
    const voteResult = await db.collection('vote_activity')
      .doc(voteId)
      .get()

    if (!voteResult.data) {
      return {
        success: false,
        message: '投票活动不存在'
      }
    }

    const voteInfo = voteResult.data

    // 检查用户是否已投票
    const userVoteResult = await db.collection('vote_record')
      .where({
        _voteId: voteId,
        openid: wxContext.OPENID
      })
      .get()

    const hasVoted = userVoteResult.data && userVoteResult.data.length > 0
    const userVoteRecord = hasVoted ? userVoteResult.data[0] : null

    // 计算总投票数
    const totalVoteResult = await db.collection('vote_record')
      .where({
        _voteId: voteId
      })
      .count()

    // 计算每个选项的票数
    const optionsWithVotes = await Promise.all(voteInfo.options.map(async (option, index) => {
      const optionVoteResult = await db.collection('vote_record')
        .where({
          _voteId: voteId,
          option: index
        })
        .count()

      return {
        ...option,
        votes: optionVoteResult.total || 0
      }
    }))

    const result = {
      ...voteInfo,
      totalVotes: totalVoteResult.total || 0,
      options: optionsWithVotes
    }

    return {
      success: true,
      data: result,
      hasVoted: hasVoted,
      userVoteRecord: userVoteRecord,
      message: '获取投票详情成功'
    }

  } catch (error) {
    console.error('获取投票详情失败:', error)
    return {
      success: false,
      message: '获取投票详情失败',
      error: error.message
    }
  }
}